package explore.hxx.binarytree.self;

import explore.hxx.binarytree.dependence.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author waxijiang
 */
public class FillRightNodePointer {

    public Node connect(Node root) {
        if (root == null) {
            return null;
        }

        Queue<Node> queue = new LinkedList<>();
        int layer = 0;
        int count = 0;

        queue.add(root);
        while (!queue.isEmpty()) {
            Node poll = queue.poll();
            if (poll.left != null) {
                queue.add(poll.left);
            }
            if (poll.right != null) {
                queue.add(poll.right);
            }
            count++;

            // 说明是每层最后的节点
            if (count == Math.pow(2, layer)) {
                poll.next = null;
                layer++;
                count = 0;
            } else {
                poll.next = queue.peek();
            }
        }
        return root;
    }
}
